<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>时钟</title>
    <style>
      #dom {
        border: 1px #ccc solid;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
      }
    </style>
  </head>
  <body>
    <!-- 重置保存 -->
    <!-- 开始保存，中心点保存，旋转在重置保存 -->
    <!-- context.restore();
        context.save(); -->
    <canvas id="dom" width="600" height="600"></canvas>
  </body>
</html>
<script>
  const dom = document.querySelector("#dom");
  const context = dom.getContext("2d");
  setInterval(() => {
    context.clearRect(0, 0, 600, 600);
    // 初始化圆心
    context.save();
    context.translate(300, 300);
    context.save();
    //   创建大圆
    context.beginPath();
    context.lineWidth = 8;
    context.arc(0, 0, 150, (Math.PI / 180) * 0, (Math.PI / 180) * 360);
    context.stroke();
    //   创建中心小圆
    context.beginPath();
    context.arc(0, 0, 5, (Math.PI / 180) * 0, (Math.PI / 180) * 360, false);
    context.stroke();
    //   绘制12个大黑
    for (let i = 0; i < 12; i++) {
      context.rotate((Math.PI / 180) * (360 / 12));
      context.moveTo(120, 0);
      context.lineTo(140, 0);
      context.stroke();
    }
    context.restore();
    context.save();
    //   绘制60个
    context.lineWidth = 1;
    for (let i = 0; i < 60; i++) {
      context.rotate((Math.PI / 180) * (360 / 60));
      context.moveTo(130, 0);
      context.lineTo(140, 0);
      context.stroke();
    }
    context.restore();
    context.save();
    //   实例化时间对象
    const time = new Date();
    const h = time.getHours() % 12;
    const m = time.getMinutes();
    const s = time.getSeconds();

    //   绘制时针
    context.beginPath();
    context.lineWidth = 8;
    context.rotate(
      (Math.PI / 180) * (360 / 12) * h +
        (Math.PI / 180) * (360 / 12) * (m / 60) -
        Math.PI / 2
    );
    context.moveTo(-20, 0);
    context.lineTo(70, 0);
    context.stroke();
    context.restore();
    context.save();

    //   绘制分针
    context.beginPath();
    context.lineWidth = 5;
    // context.strokeStyle = "#f00";
    context.rotate(
      (Math.PI / 180) * (360 / 60) * m +
        (Math.PI / 180) * (360 / 60) * (s / 60) -
        Math.PI / 2
    );
    context.moveTo(-20, 0);
    context.lineTo(80, 0);
    context.stroke();
    context.restore();
    context.save();

    //   绘制分针
    context.beginPath();
    context.lineWidth = 2;
    // context.strokeStyle = "#f0f";
    context.rotate((Math.PI / 180) * (360 / 60) * s - Math.PI / 2);
    context.moveTo(-20, 0);
    context.lineTo(100, 0);
    context.stroke();
    context.restore();
    context.save();
    context.restore();
    context.restore();
  }, 1000);
</script>
